﻿@model Wheeler.Web.ViewModels.VehicleViewModel
@using Wheeler.Web.Utility;
@using Wheeler.Common.Extensions;
@using Wheeler.Web.ViewModels;
@{
    Layout = "~/Views/Shared/_PopupLayout.cshtml";
    ViewBag.Title = Html.GetPageTitle("Auto Rickshaw Picture");
    int _VehicleID = Model == null ? 0 : Model.ID; 
    String _TempUploadedImageUrl = ViewBag.CropBoxImageUrl;
    String _Thumb_Blank = "/Content/Images/thumb_preview_blank.jpg";
    String _OriginalFileName = ViewData[AppConstants.ViewDataKeys.ORIGINAL_FILE_NAME] as String;
}
<div class="jb-page-heading">
    <h1>Upload Auto Rickshaw Picture</h1>
    @*<div>
        @if (_TempUploadedImageUrl.IsNullOrEmpty()) {
            <text>Select the auto rickshaw picture at first, don't worry about its size, we will guide you to make it correct.</text>
        }
        else {
            <text>Now use your mouse to move and resize the crop rectangle arround your photo to choose the exact area and size.</text>
        }
    </div>*@
</div>

<div class="jb-page-content">
    @if (Model == null)
    {
        @Html.WarningMessageBox("Sorry! Requested Auto Rickshaw does not exist.")
    }
    else
    {
        //if (Model.Name == AppConstants.ValueOf.UNKNOWN){
        //    Model.Name = "Your";
        //}
        <table cellpadding="0" cellspacing="0" style="border-collapse:collapse; width:100%;">
            <colgroup>
                <col style="width:600px;"/>
                @*<col style="width:543px;"/>*@
                <col />
            </colgroup>
            <tr>
                @*Left Column*@
                <td class="jb-border-right" style="vertical-align:top;  padding:5px 5px 0px 5px; width:550px;">
                    <div style="min-height:400px;">
                    <form id="frmVehiclePhoto" action="/Private/TestResult/PictureList/?VehicleID=@_VehicleID" method="post" enctype="multipart/form-data">            
                        <div>
                            <div id="trUploadControls" @{if (!_TempUploadedImageUrl.IsNullOrEmpty())
                                                         { <text> style="display:none;"</text>}}>
                                @*<div class="editor-label">Select Auto Rickshaw Picture &nbsp;</div>*@
                                <div class="editor-field">
                                    <input id="fileVehiclePhoto" type="file" name="vehiclePhoto" onchange="ValidateUpload();" class="hidden"/>
                                    <div class="input-append">
                                        <input type="text" id="VehiclePhoto_Cosmetic" placeholder="Select Auto Rickshaw Picture" />
			                            <a class="btn" onclick="$('#fileVehiclePhoto').click();">Browse</a>
                                    </div>
                                </div>
                                @*<div class="clearfix"></div>*@
                            </div>
                            @*<table cellpadding="3" cellspacing="0" style="width:100%; border-collapse:collapse;">
                                <tr id="trUploadControls" @{if (!_TempUploadedImageUrl.IsNullOrEmpty()) { <text> style="display:none;"</text>}}>
                                    <td style="width:160px;">Select your photo</td>
                                    <td><input id="fileVehiclePhoto" type="file" name="jobSeekerPhoto" onchange="ValidateUpload();" /></td>                                    
                                </tr>
                            </table>*@
                            @if (ViewData[AppConstants.ViewDataKeys.IMAGE_UPLOAD_ERROR] != null)
                            {
                                @Html.WarningMessageBox(ViewData[AppConstants.ViewDataKeys.IMAGE_UPLOAD_ERROR] as String)    
                            }
                            <input type="hidden" name="hdnWidthHeight" id="hdnWidthHeight" value="@ViewBag.WidthHeight" />
                            <input type="hidden" name="vehicleID" id="vehicleID" value="@_VehicleID" />
                            <input id="hdnCoordinates" type="hidden" value="" />
                            @*<input id="hdnProductImageID" name="productImageID" type="hidden" value="@_ProductImageID" />*@
                            <input id="hdnOriginalFileName" name="hdnOriginalFileName" type="hidden" value="@_OriginalFileName" />
                        </div>
                        @*<img id="imgjCrop" src="/Temp/Hydrangeas.jpg" title="" alt="" />*@
                        <div class="cropbox">
                            <div id="divCropBoxContainer" class="cropbox">                    
                                <img id="imgCropBox" src="@(_TempUploadedImageUrl)" alt="" @{if (_TempUploadedImageUrl.IsNullOrEmpty())
                                                                                             {<text>style="display:none;"</text>}}/>
                                <div><b>@_OriginalFileName</b></div>
                            </div>                            
                        </div>
                    </form>
                    </div>                 
                </td>
                @*Right Column*@
                <td style="vertical-align:top; padding:5px 0px 0px 5px;">
                    @{
                        String imageUrl = (ViewBag.CropBoxImageUrl as String).IsNullOrEmpty() ? _Thumb_Blank : ViewBag.CropBoxImageUrl as String;                        
                    }
                    @*<div style="overflow: hidden; width:200px; height:150px; margin-bottom:10px;">*@
                    <div style="overflow: hidden; width:300px; height:225px;">
                        <img id="imgPreview" class="jcrop-preview" src="@(imageUrl)" alt="" />
                    </div>
                    @*@if (!_TempUploadedImageUrl.IsNullOrEmpty()){
                    }*@
                    <div id="divButtons" style="margin:5px 0px 5px 0px;">
                        <button type="button" class="btn btn-primary@(_TempUploadedImageUrl.IsNullOrEmpty() ? " disabled" : String.Empty)" id="btnSave" onclick="CropAndSaveImage(this);"><i class="icon-hdd icon-white"></i> Save</button>
                        <button type="button" class="btn@(_TempUploadedImageUrl.IsNullOrEmpty() ? " disabled" : String.Empty)" id="btnCancel" onclick="CancelImageCrop(this);"><i class="icon-thumbs-down"></i> Cancel</button>
                    </div>                   
                    
                    @*Picture List Start*@
                    <div id="divThumbContainer">                    
                        <div id="divThumbLogo" class="jb-photo" style="display:@(Model.PictureFile.IsNullOrEmpty() ? "none" : "block");">
                            @*<a href="javascript:void(0);" onclick="ConformDeleteDialog(@Model.ID, this);" title="Click to Delete this Picture.">*@
                                <img id="imgVehiclePhoto" src="@ImageManager.GetVehiclePhotoUrl(Model.PictureFile)" alt="@Model.RegistrationNo Picture" title="@Model.RegistrationNo Picture" />                                
                            @*</a>*@
                        </div>                    
                    </div>
                    <div id="divPosition"></div>
                </td>
            </tr>
        </table>
        
        <div id="dialog" style="display:none;"></div>
        <div id="deleteDialog" style="display:none;">Do you really want to Delete this Logo?</div>
    }
</div>

@section PageHeadSection
{
    <link href="@Url.Content("~/Content/jquery.Jcrop.css")" rel="Stylesheet" type="text/css" />
    <link href="@Url.Content("~/Content/themes/jb-ui/jquery.ui.all.css")" rel="stylesheet" type="text/css" />
    <style type="text/css">
        .jb-page-heading{margin-bottom:0px;}
    </style>
}
        
@section JavaScriptPlaceHolder
{

    @Html.JavaScript("jquery.Jcrop.min.js", Url)
    @Html.JavaScript("jquery-ui-1.8.11.min.js", Url)
    <script language="Javascript" type="text/javascript">
        //var _VehicleID = @_VehicleID;
        var _Blank_Preview = '@(_Thumb_Blank)';
        $(document).ready(function(){
            BindImageCropper();
            $('#dialog').dialog({
                autoOpen: false, width: 400,
                buttons: {
                    "Ok": function () { $(this).dialog("close"); }
                }
            });
            $('#deleteDialog').dialog({
                autoOpen: false, width: 400,
                buttons: {
                    'Ok': function () { ShowLoadingAnimation(false); DeleteImage(); $(this).dialog("close"); },
                    'Cancel' : function() { $(this).dialog("close"); }
                }
            });            
            $('#fileVehiclePhoto').change(function () {
                $('#VehiclePhoto_Cosmetic').val($(this).val());
            });
            parent.AdjustiFrameHeight($(document).height());
            parent.ChildHideLoading();
        });
        function SetCoordinates(c) {        
            $('#hdnCoordinates').val(c.x + ',' + c.y + ',' + c.w + ',' + c.h );
        }
        var _jCropApi;
        var _ActualWidth = 0;
        var _ActualHeight = 0;
        function BindImageCropper() {
            var widthAndHeight = $('#hdnWidthHeight').val();
            if(widthAndHeight.length > 0)
            {
                if (_jCropApi) _jCropApi.destroy();
                $('#imgCropBox').Jcrop({
                    //setSelect: [0, 0, 200, 150],
                    setSelect: [0, 0, 300, 225],
                    onChange: ShowPreview,
                    onSelect: ShowPreview,
                    aspectRatio: @(ConfigReader.VehiclePhotoAspectRatio)
                    //boxWidth: 300, 
                    //boxHeight: 225
                }, function () {
                    _ActualWidth = widthAndHeight.split(',')[0];
                    _ActualHeight = widthAndHeight.split(',')[1];
                    _jCropApi = this;
                    parent.AdjustiFrameHeight($(document).height());
                });                    
            }
            else
                parent.AdjustiFrameHeight($(document).height());
        }  

        function ShowPreview(coords) {
            SetCoordinates(coords);
            if (parseInt(coords.w) > 0 && _ActualWidth > 0 && _ActualHeight > 0) {
                var rx = 300 / parseInt(coords.w);//var rx = 200 / coords.w;
                var ry = 225 / parseInt(coords.h);//var ry = 150 / coords.h;

                $('#imgPreview').css({
                    width: Math.round(rx * _ActualWidth) + 'px',
                    height: Math.round(ry * _ActualHeight) + 'px',                        
                    marginLeft: '-' + Math.round(rx * parseInt(coords.x)) + 'px',
                    marginTop: '-' + Math.round(ry * parseInt(coords.y)) + 'px'
                });
            }
        }
        function CropAndSaveImage(btn) {            
            if($(btn).attr('class').indexOf('disabled') > -1 ) return;
            var coordinates =  $('#hdnCoordinates').val();
            if(coordinates.length > 0)
            {
                var url= '@Url.PrivateUrl("CropAndSaveImage", "TestResult")';
                var data = { ID: $('#vehicleID').val(), PictureFile: $('#imgCropBox').attr('src'), CropProperty: coordinates, OriginalFileName: $('#hdnOriginalFileName').val() };
                Ajax(url, data, CropAndSaveImage_Success);
            }
            else
                $('#dialog').html('Please Select and Upload an Image first to Set it as your Profile Photo.').dialog('open'); //alert("Please Select and Upload an Image first to Set it as a Product Image."); 
        }

        function CropAndSaveImage_Success(obj){
            var image = eval(obj);
            $('#divCropBoxContainer').hide();            
            $('#btnSave').attr('disabled', true);   
            $('#divThumbLogo').show();
            $('#trUploadControls').slideDown('slow');
            //$('#divButtons').fadeOut('slow');
            $('#imgPreview').attr('src', _Blank_Preview);
            var random = Math.floor((Math.random() * 100) + 1);
            $('#imgVehiclePhoto').attr('src', image.PictureFile + '?r=' + random);
            $('#btnSave').addClass('disabled');
            $('#btnCancel').addClass('disabled');
            parent.SetLogo(image.PictureFile);
            parent.AdjustiFrameHeight('iframeImageList');
        }

        var _AnchorToDelete = null;
        var _ImageIdToDelete = 0;
        function ConformDeleteDialog(vehicleID, anchorElement) {
            _ImageIdToDelete = vehicleID;
            _AnchorToDelete = anchorElement;
            $('#deleteDialog').dialog('open');
        }
        function DeleteImage()
        {
            var url = '@Url.JobSeekerUrl("DeletePhoto", "Home")';
            var data = 'vehicleID=' + _ImageIdToDelete;
            Ajax(url, data, Delete_Success);
        }
        function Delete_Success(isDeleted){
            if(isDeleted){
                $('#divThumbLogo').hide();                
                $('#dialog').html('Your Photo Deleted Successfully.').dialog('open');//.modal({show: true});
                parent.SetLogo('@(ImageManager.GetVehiclePhotoUrl(String.Empty))');
                setTimeout(function () { $('#dialog').dialog('close'); }, 3000);
                parent.AdjustiFrameHeight('iframeImageList');
            }
            else
                $('#dialog').html('Sorry! Requested Image was not found for Delete.').dialog('open');
            HideLoadingAnimation();
        }
        function ValidateUpload() {
            if($('#fileVehiclePhoto').val().length > 0){
                ShowLoadingAnimation(false);
                $('#frmVehiclePhoto').submit();
            }
            else
                return false;
            return true;
        }
        function CancelImageCrop(btn) {
            //alert($(btn).attr('class'));
            if($(btn).attr('class').indexOf('disabled') > -1 ) return;
            $('#divCropBoxContainer').slideUp('slow');
            $('#trUploadControls').slideDown('slow');                
            //$('#divButtons').fadeOut('slow');
            $('#imgPreview').attr('src', _Blank_Preview);
            $(btn).addClass('disabled');
            $('#btnSave').addClass('disabled');
            $('#hdnCoordinates').val('');
            Ajax('@(Url.PublicUrl("DeleteTempImage", "Ajax"))', 'imagePath=@(_TempUploadedImageUrl)', 
                function (isDeleted){
                    //alert(isDeleted);
                }); 
        }
    </script>
}
